#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import cgi
import datetime
import wsgiref.handlers

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

class UserPrefs(db.Model):
  user = db.UserProperty()
  type = db.StringProperty()
  name = db.StringProperty()
  phone = db.PhoneNumberProperty()
  description = db.StringProperty()

class Order(db.Model):
  author_p = db.ReferenceProperty(UserPrefs)
  content = db.StringProperty(multiline=True)
  date = db.DateTimeProperty(auto_now_add=True)

class OrderToDriver(db.Model):
  order = db.ReferenceProperty(Order)
  driver_p = db.ReferenceProperty(UserPrefs)
  comment = db.StringProperty(multiline=True)
  date = db.DateTimeProperty(auto_now_add=True)

class MainPage(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    q = db.GqlQuery("SELECT * FROM UserPrefs WHERE user = :1", user)
    userprefs = q.get()
    if not userprefs:
      self.redirect('/profile')
    else:
      if userprefs.type == 'driver':
        self.redirect('/driverOrdersList')
      else:
        self.redirect('/userOrdersList')

class CreateOrder(webapp.RequestHandler):
  def post(self):
    order = Order()

    q = db.GqlQuery("SELECT * FROM UserPrefs WHERE user = :1", users.get_current_user())
    userprefs = q.get()
    if not userprefs:
      self.redirect('/profile')
    else:
      order.author_p = userprefs
      order.content = self.request.get('content')
      order.put()
      self.redirect('/')

class TakeOrder(webapp.RequestHandler):
  def post(self):
    try:
      orderId = int(self.request.get('orderId'))
      order = Order.get_by_id(orderId)

      if order:
        q = db.GqlQuery("SELECT * FROM UserPrefs WHERE user = :1", users.get_current_user())
        userprefs = q.get()
        if not userprefs:
          self.redirect('/profile')
        else:
          orderToDriver = OrderToDriver()
          orderToDriver.order = order
          orderToDriver.driver_p = userprefs
          orderToDriver.comment = self.request.get('comment')
          orderToDriver.put()
      else:
        self.response.out.write('Заказ не найден по id')

    except (TypeError, ValueError):
      self.response.out.write("<html><body><p>Неправильный формат id</p></body></html>")

class UserOrdersList(webapp.RequestHandler):
  def get(self):
    q = db.GqlQuery("SELECT * FROM UserPrefs WHERE user = :1", users.get_current_user())
    userprefs = q.get()
    if not userprefs:
      self.redirect('/profile')
    else:
      orders = Order.gql('WHERE author_p = :1', userprefs)
      # orders = OrderToDriver.gql('WHERE driver_p = :1', userprefs)
      values = {'orders': orders}
      self.response.out.write(template.render('templates/userOrdersList.html', values))

class DriverOrdersList(webapp.RequestHandler):
  def get(self):
    orders = db.GqlQuery("SELECT * "
                            "FROM Order "
                            "ORDER BY date DESC LIMIT 10")
    values = {
      'orders' : orders
    }
    self.response.out.write(template.render('templates/driverOrdersList.html', values))


class DeleteEmptyOrders(webapp.RequestHandler):
  def get(self):
    orders = db.GqlQuery("SELECT * "
                            "FROM OrderToDriver")
    for order in orders:
      order.delete()
    self.response.out.write(orders.count());

class DBMigrate(webapp.RequestHandler):
  len([ e.put() for e in Order.all().fetch(10)])

class Profile(webapp.RequestHandler):
  def any(self):
    user = users.get_current_user()
    q = db.GqlQuery("SELECT * FROM UserPrefs WHERE user = :1", user)
    profile = q.get()
    action = self.request.get('action')
    if action and action == 'save':
      if not profile:
        profile = UserPrefs()
      profile.user = users.get_current_user()
      profile.type = self.request.get('type')
      profile.name = self.request.get('name')
      profile.phone = db.PhoneNumber(self.request.get('phone'))
      profile.description = self.request.get('description')
      profile.put()

    values = {
      'profile' : profile
    }
    self.response.out.write(template.render('templates/profile.html', values))
  def get(self):
    self.any()
  def post(self):
    self.any()  

class ViewProfile(webapp.RequestHandler):
  def get(self):
    profile = None
    try:
      id = int(self.request.get('id'))
      profile = UserPrefs.get_by_id(id)
    except (TypeError, ValueError):
      profile = None
    self.response.out.write(template.render('templates/viewProfile.html', {'profile' : profile}))

class ProfilesList(webapp.RequestHandler):
  def get(self):
    self.response.out.write(template.render('templates/profilesList.html', {'profiles': UserPrefs.all()}))

class GetDriversOffers(webapp.RequestHandler):
  def get(self):
    orderToDrivers = []
    try:
      orderId = int(self.request.get('orderId'))
      order = Order.get_by_id(orderId) # todo do we really nead to run the query and cannot use just orderId?
      orderToDrivers = OrderToDriver.gql("WHERE order = :1", order)
    except (TypeError, ValueError):
      orderToDrivers = []
    self.response.out.write(template.render('templates/getDriversOffers.html', {'orderToDrivers': orderToDrivers}))

application = webapp.WSGIApplication([
  ('/', MainPage),
  ('/createOrder', CreateOrder),
  ('/takeOrder', TakeOrder),
  ('/deleteEmptyOrders', DeleteEmptyOrders),
  ('/userOrdersList', UserOrdersList),
  ('/driverOrdersList', DriverOrdersList),
  ('/profilesList', ProfilesList),
  ('/profile', Profile),
  ('/viewProfile', ViewProfile),
  ('/getDriversOffers', GetDriversOffers),
  ('/dbMigrate', DBMigrate)
], debug=True)


def main():
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()
